import React, { useState, createContext } from 'react'
import classNames from 'classnames'
import { type MenuProps, type IMenuContext, MenuItemProps } from './types'
// import Item from './menuItem'
export const MenuContext = createContext<IMenuContext>({ index: '0' })

export const Menu: React.FC<MenuProps> = ({
	defaultIndex,
	className,
	mode,
	style,
	onSelect,
	children,
	defaultOpenSubMenus
}) => {
	const [currentActive, setCurrentActive] = useState<string>(defaultIndex!)
	const classes = classNames('v-menu', className, {
		'menu-vertical': mode === 'vertical',
		'menu-horizontal': mode !== 'vertical'
	})

	const handleClick = (index: string) => {
		setCurrentActive(index)
		if (onSelect) {
			onSelect(index)
		}
	}
	const passedContext: IMenuContext = {
		index: currentActive ? currentActive : '0',
		onSelect: handleClick,
		mode,
		defaultOpenSubMenus
	}

	const renderChildren = () => {
		return React.Children.map(children, (child, index) => {
			const childElement =
				child as React.FunctionComponentElement<MenuItemProps>

			const { displayName } = childElement.type
			if (displayName === 'MenuItem' || displayName === 'SubMenu') {
				return React.cloneElement(childElement, { index: index + '' })
			} else {
				console.error(
					'Warning: Menu as a child which is not a MenuItem component'
				)
			}
		})
	}
	return (
		<ul className={classes} style={style} data-testid="test-menu">
			<MenuContext.Provider value={passedContext}>
				{renderChildren()}
			</MenuContext.Provider>
		</ul>
	)
}

// Menu.Item = Item

Menu.defaultProps = {
	defaultIndex: '0',
	mode: 'horizontal',
	defaultOpenSubMenus: []
}

export default Menu
